import BaseReact from "../baseReact";
import {GetQtController} from "../../QtUtils";
import {PUBSUB_KEY_TOOLWEBSHOW_CHANGED} from "../../QtBaseController";
export default class ToolLabel extends BaseReact{
  constructor(props) {
    super(props);
    this.unique_name = 'ToolLabel'
    this.state={
      isToolWebShow:false,
      isNeedLoad:false,
    }
  }
  onCreated() {
    window.addEventListener("message", this._receiveMessage.bind(this), false);
    this.isNeedLoad = (GetQtController().inParam.toolWebUrl != '');
  }
  onMounted() {
    if(this.isNeedLoad) {
      let strSrc = GetQtController().inParam.toolWebUrl;
      strSrc += '?commonHost=' + GetQtController().inParam.toolServerUrl;
      strSrc += "&isClient=1&isFrame=1";
      // strSrc += "&project_name=" + GetQtController().inParam.strProjectName;
      this.refs.toolLabelIframe.src = strSrc;

      this.refs.toolLabelIframe.onload = function() {
        console.log('1111111--onload',GetQtController().inParam.toolProjectName)
        this._postMessage('VS_SetProjectName',[GetQtController().inParam.toolProjectName]);
      }.bind(this);
    }
  }
  onDestroyed() {
    window.removeEventListener("message",this._receiveMessage);
  }
  onPubSubMessage(strCode,data) {
    if(strCode == 'VS_SetPointPos' || strCode == 'VS_SetProjectName') {
      this._postMessage(strCode,data);
    }else if(strCode == PUBSUB_KEY_TOOLWEBSHOW_CHANGED) {
      // this.isToolWebShow = data;
      this.setState({
        isToolWebShow:data
      })
      GetQtController().Web_ToolWebShow(data);
    }
  }
  _postMessage(strCode,data) {
    if(this.isNeedLoad) {
      let postData = {};
      postData['key'] = 'ToIFrameQtMessage';
      postData['code'] = strCode;
      postData['data'] = data;
      this.refs.toolLabelIframe.contentWindow.postMessage(postData,'*');
    }
  }

  _receiveMessage(messageEvent) {
    if(messageEvent.data != undefined && messageEvent.data.key == 'iframeMessage') {
      let strJsonData = messageEvent.data.data;
      if(!this.state.isToolWebShow) {
        return;
      }
      GetQtController().ToQtCommand(strJsonData);
    }
  }




  render() {
    if(GetQtController().inParam.toolWebUrl != '') {
      return <div>
        <div id="ToolLabel" style={{display:this.state.isToolWebShow?'block':'none'}}>
          <iframe className="IframStyle" ref="toolLabelIframe"
                  sandbox="allow-forms allow-scripts allow-same-origin allow-popups allow-top-navigation" scrolling="no"
                  frameBorder="0" src="" style={{width: 1920,height: 1080,position: 'absolute',top: 0,left: 0,zIndex: 999}}></iframe>
        </div>
      </div>;
    }else {
      return <div></div>
    }

  }
}
